package com.itheima.pay.wechat;

import com.alipay.api.internal.util.file.IOUtils;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("wechat")
public class WeChatPayController {

    // 加载微信的配置
    @Autowired
    WXPayConfigCustom config;


    /**
     * 支付回调通知
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping("notify")
    public String payNotify(HttpServletRequest request, HttpServletResponse response) {
        try {
            String xmlResult = IOUtils.toString(request.getInputStream(), request.getCharacterEncoding());
            Map<String, String> map = WXPayUtil.xmlToMap(xmlResult);
            // 加入自己处理订单的业务逻辑，需要判断订单是否已经支付过，否则可能会重复调用
            String orderId = map.get("out_trade_no");
            String tradeNo = map.get("transaction_id");
            String totalFee = map.get("total_fee");
            String returnCode = map.get("return_code");
            String resultCode = map.get("result_code");
            return "OK";
        } catch (Exception e) {
            //log.error("微信回调结果异常,异常原因{}", e.getMessage());
            return "ERROR";
        }
    }

    /**
     * 下单生成二维码
     *
     * @param out_trade_no
     */
    @GetMapping("precreate/{out_trade_no}")
    public Map<String, String> precreate(@PathVariable("out_trade_no") String out_trade_no) {

        try {
            //初始化wxpay
            WXPay wxPay = new WXPay(config);

            //封装参数map
            Map<String, String> reqData = new HashMap<>();
            reqData.put("body", "黑马餐饮-消费");
            reqData.put("out_trade_no", out_trade_no);
            reqData.put("total_fee", "10"); //单位：分
            reqData.put("spbill_create_ip", "123.12.12.123");
            reqData.put("notify_url", "http://127.0.0.1:8080/wechat/notify"); //微信回调url, 使用内网穿透：http://127.0.0.1:8080
            reqData.put("trade_type", "NATIVE");

            //发起http远程调用
            Map<String, String> map = wxPay.unifiedOrder(reqData);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }


    @GetMapping("query/{out_trade_no}")
    public Map<String, String> query(@PathVariable("out_trade_no") String out_trade_no) {

        //初始化wxpay
        try {
            WXPay wxPay = new WXPay(config);

            Map<String, String> reqData = new HashMap<>();

            reqData.put("out_trade_no", out_trade_no);

            Map<String, String> map = wxPay.orderQuery(reqData);
            //交易成功判断条件： return_code、result_code和trade_state都为SUCCESS
            String return_code = map.get("return_code");
            String result_code = map.get("result_code");
            String trade_state = map.get("trade_state");
            if ("SUCCESS".equals(return_code) && "SUCCESS".equals(result_code) && "SUCCESS".equals(trade_state)) {
                // 成功
            }
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;

    }


    @GetMapping("refund/{out_trade_no}/{out_refund_no}")
    public   Map<String, String>  refund(@PathVariable("out_trade_no") String out_trade_no,
                                         @PathVariable("out_refund_no") String out_refund_no) {
        try {
            WXPay wxPay = new WXPay(config);

            Map<String, String> reqData = new HashMap<>();
            reqData.put("out_trade_no", out_trade_no);
            reqData.put("out_refund_no", out_refund_no);
            reqData.put("total_fee", "10"); //订单金额
            reqData.put("refund_fee", "10"); //退款金额

            Map<String, String> map = wxPay.refund(reqData);
            return map;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    @GetMapping("refundquery/{out_trade_no}/{out_request_no}")
    public void refundQuery(@PathVariable("out_trade_no") String out_trade_no, @PathVariable("out_request_no") String out_request_no) {

    }

}
